<template>
	<div class="system-role-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px" v-if="state.dialog.isShowDialog">
			<el-form ref="cateDialogFormRef" :model="state.ruleForm" size="default" label-width="120px" :rules="state.rules">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="上级分类">
							<el-cascader
								:options="state.treeList"
								:props="{ checkStrictly: true, value: 'id', label: 'name' }"
								placeholder="请选择上级分类"
								clearable
								class="w100"
								v-model="state.ruleForm.parentid"
								:disabled="state.type === 'view' || state.ruleForm.parent_id === 0"
							>
								<template #default="{ node, data }">
									<span>{{ data.name }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="中文分类名称" prop="name">
							<el-input v-model="state.ruleForm.name" placeholder="请输入分类名称" clearable :disabled="state.type === 'view'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="英文分类名称" prop="en_name">
							<el-input v-model="state.ruleForm.en_name" placeholder="请输入分类名称" clearable :disabled="state.type === 'view'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="分类状态" prop="status">
							<el-radio-group v-model="state.ruleForm.status" class="w100" :disabled="state.type === 'view'">
								<el-radio-button label="normal">启用</el-radio-button>
								<el-radio-button label="disable">禁用</el-radio-button>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="排序" prop="sort">
							<el-input-number v-model="state.ruleForm.sort" :min="0" :max="999" controls-position="right" placeholder="请输入排序" class="w100" :disabled="state.type === 'view'"/>
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="分类图片" prop="img">
							<UploadFile
								@uploadSuccess="uploadSuccess"
								@uploadRemove="uploadRemove"
								:limit="1"
								acceptSuffix=".bmp,.jpg,.png"
								:imgList="state.fileList"
                :isDisabled="state.type === 'view'"
							></UploadFile>
						</el-form-item>
					</el-col> -->
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default" v-show="state.type != 'view'">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemRoleDialog">
import { reactive, ref, nextTick, defineAsyncComponent } from 'vue';
import { cateDetail, addCate, updateCate } from '/@/api/cate';
import { ElMessage } from 'element-plus';

const UploadFile = defineAsyncComponent(() => import('/@/components/uploadFile/index.vue'));

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义父组件向子组件传值
const props = defineProps({
	id: { type: Number, required: false, default: 0 },
});

// 定义变量内容
const cateDialogFormRef = ref();
const state = reactive({
	id: 0,
  type: '',
	fileList: <EmptyArrayType>[],
	ruleForm: <EmptyObjectType>{
    status: 'normal',
		parentid: []
  },
	rules: {
		name: [
			{
				required: true,
				message: '请输入中文分类名称',
				trigger: 'blur',
			},
		],
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	treeList: [] as any
});

// 取消
const initForm = () => {
	state.ruleForm = <EmptyObjectType>{
    status: 'normal',
		parentid: []
  };
};

// 打开弹窗
const openDialog = (type: string, id: any, treeList?: any, parentid?:string) => {
	state.treeList = treeList;
	if (type === 'edit') {
		state.id = id;
		state.dialog.title = '修改分类';
		state.dialog.submitTxt = '修 改';
	} else if(type === 'add') {
		initForm();
		state.id = 0;
		state.dialog.title = '新增分类';
		state.dialog.submitTxt = '新 增';
		state.fileList = [];
	} else if(type === 'addNext') {
		initForm();
		state.id = 0;
		let parentIds = parentid ? parentid.split(','):[];
		let arrOfNumbers = parentIds.map(s => {  
			let num = Number(s);  
			return isNaN(num) ? null : num; // 或者你可以选择替换为其他默认值或抛出错误  
		});
		arrOfNumbers.push(id);
		state.ruleForm.parentid = arrOfNumbers;
		state.dialog.title = '新增分类';
		state.dialog.submitTxt = '新 增';
		state.fileList = [];
	} else if(type === 'view') {
		state.id = id;
		state.dialog.title = '查看分类';
		state.dialog.submitTxt = '修 改';
	} 
  state.type = type;
	state.dialog.isShowDialog = true;
	// 清空表单，此项需加表单验证才能使用
	nextTick(() => {
		cateDialogFormRef.value.resetFields();
		cateDialogFormRef.value.clearValidate();
	});
	if (state.id && (state.type === 'edit' || state.type === 'view')) {
		getCateDetail();
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
	cateDialogFormRef.value.validate((valid: boolean, fields: EmptyArrayType) => {
		if (valid) {
			if (state.id) {
				updateCate(state.ruleForm).then((res: any) => {
					if (res.status === 'success') {
						initForm();
						closeDialog();
						emit('refresh');
					} else {
						ElMessage.error(res.msg);
					}
				});
			} else {
				addCate(state.ruleForm).then((res: any) => {
					if (res.status === 'success') {
						initForm();
						closeDialog();
						emit('refresh');
					} else {
						ElMessage.error(res.msg);
					}
				});
			}
		} else {
			return false;
		}
	});
};
// 获取壁纸详情数据
const getCateDetail = () => {
	cateDetail(state.id).then((res: any) => {
		if (res.status === 'success') {
			let parentIds = res.data.parentid ? res.data.parentid.split(','):[];
			let arrOfNumbers = parentIds.map(s => {  
				let num = Number(s);  
				return isNaN(num) ? null : num; // 或者你可以选择替换为其他默认值或抛出错误  
			});
			res.data.parentid = arrOfNumbers;
			state.ruleForm = res.data;
			state.fileList = [{ url: res.data.img }];
			// 修改的时候，禁用上级自己选自己
			disabledSelf(state.treeList);
		} else {
			ElMessage.error(res.msg);
		}
	});
};

// 递归禁用
const disabledSelf = (treeList:any) => {
  for(let i = 0; i < treeList.length; i++){
		treeList[i].disabled = false;
		if(treeList[i].id == state.ruleForm.id) {
			treeList[i].disabled = true;
			break;
		} 
		if(treeList[i].children && treeList[i].children.length) {
			disabledSelf(treeList[i].children);
		}	
  }
	return treeList;
}

// 上传成功
const uploadSuccess = (res: any, file: any) => {
	if (res.length > 0) {
		state.ruleForm.img = res[0].url;
	}
};
// 删除图片
const uploadRemove = (res: any, file: any) => {
	state.ruleForm.img = '';
};

// 分类改变
const changeCate = (option: any) => {
	let cateInfo: any = props.cateList.find((item: any) => item.value == option);
	state.ruleForm.catename = cateInfo.label;
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.system-role-dialog-container {
	.menu-data-tree {
		width: 100%;
		border: 1px solid var(--el-border-color);
		border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
		padding: 5px;
	}
}
</style>
